package com.felix.apigw;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.actuate.GatewayLegacyControllerEndpoint;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class FileRefreshListener implements ApplicationListener<RefreshRoutesEvent> {
    @Autowired
    private GatewayLegacyControllerEndpoint gatewayLegacyControllerEndpoint;
    private final ObjectMapper objectMapper = new ObjectMapper();
    final Configuration configuration = Configuration.builder()
            .jsonProvider(new JacksonJsonProvider(objectMapper))
            .mappingProvider(new JacksonMappingProvider(objectMapper))
            .build();

    @Value("${gateway.base.path:}")
    private String basePath;
    @Value("${gateway.config.file:gateway.json}")
    private String gatewayConfigFile;

    @Override
    public void onApplicationEvent(RefreshRoutesEvent refreshRoutesEvent) {
        gatewayLegacyControllerEndpoint.routes().doOnNext(maps -> {
            try {
                String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(maps);
                String configInfo = ConfigJsonParser.getConfig(json);
                File file = new File(basePath, gatewayConfigFile);
                if (!file.exists()) {
                    file.createNewFile();
                }
                String oldFileString = FileUtils.readFileToString(file);
                if (!oldFileString.equals(configInfo)) {
                    FileUtils.writeByteArrayToFile(file, configInfo.getBytes(StandardCharsets.UTF_8));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).subscribe();
    }
}
